from osv import fields,osv
import mx.DateTime
import tools.sql
from tools.translate import _

class kdvn_payment_vat_invoice_for_revenue(osv.osv):
    _name = 'kdvn.payment.vat.invoice.for.revenue'
    _description = 'KDVN Payment VAT Invoice For Revenue'
    _rec_name = 'payment_id'
    _auto=False
    _columns={
              'payment_id':fields.many2one('kdvn.payment.from.client','Client Payment'),
              'amount_e':fields.float('Amount E.'),
              'amount_m':fields.float('Amount M.'),
              'taxes_percent':fields.integer('VAT (%)'),
              'vat_invoice_id':fields.many2one('kdvn.red.invoice','VAT No.',required=True),
              'allocated':fields.float('Allocated',help='This amount is not included VAT'),
              'note':fields.char('Note',size=255)
              }

    def init(self,cr):
        cr.execute("Create or replace view kdvn_payment_vat_invoice_for_revenue as Select \
                    kpvt.id as id,\
                    kpfc.id as payment_id,\
                    amount_e,\
                    amount_m,\
                    taxes_percent,\
                    vat_invoice_id,\
                    kpvt.amount/(1+taxes_percent/100.0) as allocated,\
                    kpvt.note\
                from\
                    kdvn_payment_from_client kpfc\
                left join\
                    kdvn_payment_vat_invoice kpvt on  kpfc.id = kpvt.payment_id\
                where vat_invoice_id is not null")
kdvn_payment_vat_invoice_for_revenue()

class kdvn_project_revenue_report(osv.osv):
    _name='kdvn.project.revenue.report'
    _description='KDVN Project revenue'
    _auto=False
    
#    def _read_flat(self, cr, user, ids, fields, context=None, load='_classic_read'):
#        res = self._read_flat(self, cr, user, ids, fields, context)
#        raise osv.except_osv("E",res)
#        return res

    def _get_link_contract_kindenvat_expense(self,cr,uid,ids,prop, unknow_none,unknow_dict):
        res = {}
        if ids:
            for id in ids:
                res[id]={'contract_ids':[],'kpayment_vat_id':[]}
            prj_ids = ",".join(map(str,ids))
            cr.execute("Select project_id,contract_id from vwcontract_for_calcualate_revenue where project_id in (%s)" % (prj_ids))          
            for prj_id, contract_id in cr.fetchall():
                res[prj_id]['contract_ids'].append(contract_id)
            
            cr.execute("Select \
                            project_id,\
                            kpvi.id\
                        from \
                            (Select \
                                distinct project_id,contract_id\
                            from\
                                (Select\
                                    project_e_id as project_id,\
                                    contract_id\
                                from\
                                    sale_order so\
                                where\
                                    so.state='done'\
                                union\
                                Select\
                                    project_m_id as project_id,\
                                    contract_id\
                                from\
                                    sale_order so\
                                where\
                                    so.state='done') vwtemp \
                            where\
                                contract_id is not null and project_id is not null) so \
                        left join \
                            kdvn_payment_from_client kpfc on so.contract_id = kpfc.contract_id\
                        left join \
                            kdvn_payment_vat_invoice_for_revenue kpvi on kpfc.id = kpvi.payment_id\
                        where\
                            vat_invoice_id is not null and project_id in (%s);" % prj_ids)
            for prj_id, kpvi_id in cr.fetchall():
                res[prj_id]['kpayment_vat_id'].append(kpvi_id)
        else:
            res = {'value':{}}
            #raise osv.except_osv("E",res)
        return res
    
    _columns={
            'project_id':fields.many2one('kdvn.project','Project'),
            'project_type':fields.selection([('E','Electrical'),('M','Mechanical')],"Project Type",select=1,required=True),
            'revenue_int':fields.float('Revenue INT.'),
            'revenue_vn':fields.float('Revenue VN.'),
            'total_budget':fields.float('Total Budget'),
            'material_payment_vnd':fields.float('Material'),
            'site_expense_payment_vnd':fields.float('Site Expense'),
            'sub_contractor_payment_vnd':fields.float('Sub-Contractor'),
            'gse_payment_vnd':fields.float('G.S.E.',help='General Site Expense, Japan Indirect Cost, Local staff salary'),
            'kfp_payment_vnd':fields.float('JP. Expense',help="Kinden's commision and Japan supervisor fee"),
            'profit_payment_vnd':fields.float('Profit'),
            'contract_ids':fields.function(_get_link_contract_kindenvat_expense,type='one2many',relation='kdvn.contract.client',string='Contracts',method=True,multi='get_links'),
            'kpayment_vat_id':fields.function(_get_link_contract_kindenvat_expense,type='one2many',relation='kdvn.payment.vat.invoice.for.revenue',string='Payment & VAT Invoice',method=True,multi='get_links')
              }
kdvn_project_revenue_report()
